You should use the if statement if you want to execute some code if a condition is true.
if (condition)
{
code to be executed if condition is true
} |
<script type="text/javascript"> //If the time on your browser is less than 10, //you will get a "Good morning" greeting. var d=new Date()
var time=d.getHours()
if (time<10)
{
document.write("<b>Good morning</b>")
}
</script> |
Notice that there is no ..else.. in this syntax. You just tell the code to execute some code if the condition is true.
If you want to execute some code if a condition is true and another code if a condition is false, use the if....else statement.
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is false
} |
<script type="text/javascript"> //If the time on your browser is less than 10, //you will get a "Good morning" greeting. //Otherwise you will get a "Good day" greeting. var d = new Date()
var time = d.getHours()
if (time < 10)
{
document.write("Good morning!")
}
else
{
document.write("Good day!")
}
</script> |
#Title: Conditional Statements
#Element: 171: Conditional Statements